//
//  OALoginViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "MainTabBarController.h"
#import "findpasswordfirstViewController.h"
#import "zucexinxiViewController.h"
#import "findpasswordViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "OALoginViewController.h"
#import "MainViewController.h"
#import "XmlParseHelper.h"
//#import "AuthHelper.h"
#import "webViewController.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "ZLCGuidePageView.h"
#import "wmimaViewController.h"
@interface OALoginViewController ()<UITextFieldDelegate>
//@property (nonatomic, strong) AuthHelper *helper;
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSDictionary * dic2;
@end

@implementation OALoginViewController
short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"122.224.123.170";  //vpn设备IP地址
NSString *userName = @"ccpitzjapp";             //用户名认证的用户名
NSString *password = @"ccpitzjappapp";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书


- (void)viewDidLoad {


    [super viewDidLoad];
    
    [_yuyan setTitle:NSLocalizedString(@"切换语言", nil) forState:UIControlStateNormal];

    if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
//引导页图片数组
//    NSArray *images =  @[[UIImage imageNamed:@"1、宣传页面-1（750x1334）"],[UIImage imageNamed:@"1、宣传页面-2（750x1334）"]];
//    //创建引导页视图
//    ZLCGuidePageView *pageView = [[ZLCGuidePageView alloc]initWithFrame:self.view.frame WithImages:images];
//    [self.view addSubview:pageView];

}
[_loginbutton setTitle:NSLocalizedString(@"登录页面-登陆", nil) forState:UIControlStateNormal];
[_setinbutton setTitle:NSLocalizedString(@"登录页面-注册", nil) forState:UIControlStateNormal];
[_forgetbutton setTitle:NSLocalizedString(@"登录页面-忘记密码", nil) forState:UIControlStateNormal];
_accountTextField.placeholder =NSLocalizedString(@"请输入用户名", nil);
_passwordTextField.placeholder =NSLocalizedString(@"请输入密码", nil);
   NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
if ([language isEqualToString:@"0"]) {
_righttitle.constant = 40;
_lefttitle.constant = 40;
    _titleimage.x = 40;
    _titleimage.width = KScreenWidth -80;
}else{
_righttitle.constant = 20;
_lefttitle.constant = 20;
    _titleimage.x = 20;
    _titleimage.width = KScreenWidth -40;
}
_titleimage.image = [UIImage imageNamed:NSLocalizedString(@"登录-name", nil)];
    self.rememberbutton.selected = YES;
    
        // Do any additional setup after loading the view.
// NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
//
//[UIColor whiteColor],NSForegroundColorAttributeName, nil];
// 
//[self.navigationController.navigationBar setTitleTextAttributes:attributes];
// self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
//UIBarButtonItem * backButtonItem = [[UIBarButtonItem alloc] init];
//backButtonItem.title = @"返回";
//self.navigationItem.backBarButtonItem = backButtonItem;  // 登陆按钮
[_buttonlayer.layer setMasksToBounds:YES];

[_buttonlayer.layer setCornerRadius:40.0];//设置矩形四个圆角半径

[_buttonlayer.layer setBorderWidth:2.0];//边框宽度
UIColor *textColor = self.view.tintColor;

UIColor *color = [[UIColor blueColor]colorWithAlphaComponent:.7];
_buttonlayer.layer.borderColor=textColor.CGColor;

    UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"密码"]];
      image1.frame = CGRectMake(10, 5, 20, 20);
    
//image1.transform = CGAffineTransformMakeTranslation(30, 0);
       //image1.contentMode = UIViewContentModeTopLeft;
   UIView *view1 = [[UIView alloc]init];
   view1.backgroundColor = [UIColor whiteColor];
   view1.size = CGSizeMake(30,30);
   [view1 addSubview:image1];
    self.passwordTextField.leftView = view1;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"用户名"]];
 image2.frame = CGRectMake(10, 5, 20, 20);
  UIView *view2 = [[UIView alloc]init];
   view2.backgroundColor = [UIColor whiteColor];
   view2.size = CGSizeMake(30,30);
   [view2 addSubview:image2];

 
    self.accountTextField.leftView = view2;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;

 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] !=0) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] !=0) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
        self.autobutton.selected = YES;
    }
     // 判断版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
 CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
 // app版本
_verson= [infoDictionary objectForKey:@"CFBundleShortVersionString"];
[self _shadow];
}
-(void)viewWillAppear:(BOOL)animated{
// self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
}


- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (void)_shadow{
 _accountTextField.layer.shadowOffset =  CGSizeMake(5,5);
    _accountTextField.layer.shadowOpacity = 0.75;
    _accountTextField.layer.shadowColor = [UIColor colorWithHexString:@"0436be" ].CGColor;
_accountTextField.layer.shadowRadius = 5;


}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setin{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

[self.accountTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
     NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
         strUrl = [strUrl lowercaseString];
      NSString *password =  [ self md5:self.passwordTextField.text];
NSString *website = [[NSUserDefaults standardUserDefaults] objectForKey:@"website"];
   NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];
NSString *bodyStr = [NSString stringWithFormat:@"<?xml version='1.0' encoding='UTF-8'?><message><header><userName>administrator</userName><password>b628e2c3b78ef9bf269c489b35176e48</password><website>%@</website><language>%@</language><type>%@</type></header><body><loginName>%@</loginName><password>%@</password><pscode>%@</pscode></body></message>",website,language,BAtype,strUrl,password,self.passwordTextField.text];
  bodyStr= [bodyStr URLEncodedString];
 NSArray * array = @[@{@"arg0":bodyStr}];
    NSString * path = [NSString stringWithFormat:@"%@%@",BAip,blogin];
  [HttpTools requestWithURL:path arrays:array method:@"login" success:^(id JSON) {
  
//                    NSDictionary *dic0 = JSON[@"company"];
//                    NSMutableArray *array0 = [NSMutableArray array];
//                    for (int i=0;i<30000;i++) {
//    [array0 addObject:dic0];
//}
//NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//        dic[@"type"] = array0;
//NSDictionary *dic00  = dic;
//             [[NSUserDefaults standardUserDefaults] setObject:dic00 forKey:@"dic0"];
//      
//     [[NSUserDefaults standardUserDefaults] synchronize];

  NSLog(@"%@",JSON);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
                  [self.view makeToast:JSON[@"msg"]];
                  if([[NSString stringWithFormat:@"%@",JSON[@"code"]] isEqualToString:@"200"]){
                  NSDictionary *dic = JSON[@"userInfo"];
             [[NSUserDefaults standardUserDefaults] setObject:dic[@"password"] forKey:@"password"];
//             [[NSUserDefaults standardUserDefaults] setObject:JSON[@"productnum"] forKey:@"productnum"];
//             [[NSUserDefaults standardUserDefaults] setObject:JSON[@"receivenum"] forKey:@"receivenum"];
//             [[NSUserDefaults standardUserDefaults] setObject:JSON[@"demandnum"] forKey:@"demandnum"];
             [[NSUserDefaults standardUserDefaults] setObject:dic[@"id"] forKey:@"uid"];
             [[NSUserDefaults standardUserDefaults] setObject:dic[@"uname"] forKey:@"uname"];
             [[NSUserDefaults standardUserDefaults] setObject:dic[@"phone"] forKey:@"phone"];
             [[NSUserDefaults standardUserDefaults] setObject:dic[@"email"] forKey:@"email"];

if([[JSON allKeys] containsObject:@"company"])

{
   [[NSUserDefaults standardUserDefaults] setObject:JSON[@"company"][@"name"] forKey:@"companyName"];

   [[NSUserDefaults standardUserDefaults] setObject:JSON[@"company"][@"id"] forKey:@"cpid"];
}else{


}

               [[NSUserDefaults standardUserDefaults] setObject:dic[@"username"] forKey:@"userName"];

                  [[NSUserDefaults standardUserDefaults] setObject:dic[@"type"] forKey:@"type"];

            
                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
        [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];


                       DanLi *danli = [[DanLi alloc] init];
    danli.stay = @"yes";
    danli.value = @"no";
//                        MenuViewController *tar = [[MenuViewController alloc]init];
                        MainTabBarController *tar = [[MainTabBarController alloc]init];
               self.view.window.rootViewController = tar;
                  }

  } failure:^(NSError *error) {
      [MBProgressHUD hideHUDForView:self.view animated:YES];

    }];


}
- (IBAction)back:(id)sender {
    MainTabBarController  *tar = [[MainTabBarController alloc]init];
      DanLi *danli = [[DanLi alloc] init];
          danli.value = @"no";

               self.view.window.rootViewController = tar;


}

- (IBAction)yuyanaction:(id)sender {
   NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"language"];

if([language isEqualToString:@"0"]){
      [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"language"];
           [[NSUserDefaults standardUserDefaults] setObject:@"2" forKey:@"website"];

    [self changeLanguageTo:@"en"];
MainTabBarController *tar = [[MainTabBarController alloc]init];

                   self.view.window.rootViewController = tar;

}else{
  [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"language"];
    [self changeLanguageTo:@"zh-Hans"];
MainTabBarController *tar = [[MainTabBarController alloc]init];
                          [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"website"];

                   self.view.window.rootViewController = tar;

}


}
- (void)changeLanguageTo:(NSString *)language {
    // 设置语言
    [NSBundle setLanguage:language];
    
    // 然后将设置好的语言存储好，下次进来直接加载
    [[NSUserDefaults standardUserDefaults] setObject:language forKey:@"myLanguage"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    // 我们要把系统windown的rootViewController替换掉
//    ZHTabBarController *tab = [[ZHTabBarController alloc] init];
//    [UIApplication sharedApplication].keyWindow.rootViewController = tab;
//    // 跳转到设置页
//    tab.selectedIndex = 2;
}
- (IBAction)LoginAction:(id)sender {
//if ([_type isEqualToString:@"1"]) {
//    [self setin ];
//}
//else{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

if (self.accountTextField.text.length == 0) {
        [self.view makeToast:NSLocalizedString(@"请输入账号", nil)];
        return;
    } 
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:NSLocalizedString(@"请输入密码", nil)];
        return;
    }
else{
 MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = NSLocalizedString(@"正在登录,请稍等", nil);
                [NSThread sleepForTimeInterval:1.0];


                 [self setin];

                 }

//}


}
- (IBAction)rememberbutton:(id)sender {
 self.rememberbutton.selected = !self.rememberbutton.selected;
    if (!self.rememberbutton.selected) {
        self.autobutton.selected = self.rememberbutton.selected;
    }
    

}

- (IBAction)autonbutton:(id)sender {
    self.autobutton.selected = !self.autobutton.selected;


//在此实现不打勾时的方法
}
- (IBAction)zhuce:(id)sender {
findpasswordViewController *VC = [[findpasswordViewController alloc]init];



        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:VC];

//[self.navigationController pushViewController:VC animated:YES];
      DanLi *danli = [[DanLi alloc] init];
          danli.value = @"no";

               self.view.window.rootViewController = navVC;
}

- (IBAction)wangjimima:(id)sender {
zucexinxiViewController *VC = [[zucexinxiViewController alloc]init];

        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:VC];

//[self.navigationController pushViewController:VC animated:YES];
      DanLi *danli = [[DanLi alloc] init];
          danli.value = @"no";

               self.view.window.rootViewController = navVC;
}
@end
